var wrapCopyContent = function (content, isHtml) {
    var separator = "\r\n";
    if (isHtml) {
        separator = "<br/>";
    }
    var copyTemplate =
        "【复制内容】：" +
        separator +
        content +
        separator +
        "--------------------------------------" +
        separator +
        "俺发现你在复制内容啦";
    return copyTemplate;
};

var appendLicenseWhenCopy = function (content, bloger, license, isHtml) {
    var separator = "\r\n";
    if (isHtml) {
        separator = "<br/>";
    }
    var copyTemplate = content + separator + "————————————————" + separator;
    copyTemplate +=
        "版权声明：本文为博主「" +
        bloger +
        "」的原创文章，遵循" +
        license +
        "版权协议，转载请附上原文出处链接及本声明。" +
        separator;
    copyTemplate += "原文链接：" + location.href;
};

/**
 * 获取选择的文本内容
 */
var getSelectContent = function (event) {
    var selection = window.getSelection();
    // var selection = document.getSelection(); eq
    // var selectContent = selection.getRangeAt(0).cloneContents().textContent;  eq
    var selectContent = selection.toString();

    selectContent = wrapCopyContent(selectContent);
    console.log("select content:" + selectContent);
    document.getElementById("output").value = selectContent;
};

/**
 * 变更选择的文本内容
 */
var changeSelectContent = function (event) {
    var selection = window.getSelection();
    var selectContent = selection.getRangeAt(0).cloneContents().textContent;
    var textData = wrapCopyContent(selectContent);
    var htmlData = wrapCopyContent(selectContent, true);

    if (window.clipboardData) {
        // Internet Explorer
        window.clipboardData.setData("text", textData);
        return;
    }

    var newDiv = document.createElement("div");
    newDiv.style.position = "fixed";
    newDiv.style.left = "-99999px";
    document.body.appendChild(newDiv);
    newDiv.innerHTML = htmlData;
    selection.selectAllChildren(newDiv);
    window.setTimeout(function () {
        document.body.removeChild(newDiv);
    }, 0);
    document.execCommand("copy");
};

/**
 * 变更选择的文本内容
 */
var changeSelectContent2 = function (event) {
    var selection = window.getSelection();
    var selectContent = selection.getRangeAt(0).cloneContents().textContent;
    var textData = wrapCopyContent(selectContent);
    var htmlData = wrapCopyContent(selectContent, true);

    if (event.clipboardData) {
        event.clipboardData.setData("text/html", htmlData);
        //setData(剪贴板格式, 数据) 给剪贴板赋予指定格式的数据。返回 true 表示操作成功。
        event.clipboardData.setData("text/plain", textData);
    } else if (window.clipboardData) {
        //Internet Explorer
        return window.clipboardData.setData("text", textData);
    }
};

var handleCopyText = function (event) {
    getSelectContent(event);
    changeSelectContent(event);
    // changeSelectContent2(event);
};

document.oncopy = handleCopyText;
